<?php

namespace app\controllers;

use app\components\WebController;
use app\models\Comment;
use app\models\Like;
use app\models\Post;
use yii\web\NotFoundHttpException;

class PostController extends WebController {

    public $layout = 'detail';

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }
        if ($action->id === 'index') {
            $cid = $this->getParam('cid');
            if (NULL === $cid) {
                \Yii::$app->request->setQueryParams(['cid' => Post::CID_TECH]);
            }
        }
        return TRUE;
    }

    public function render($params = [], $view = NULL) {
        if ($this->action->id === 'comment') {
            $model = Post::findOne(intval($this->get('id')));
            if (!$model) {
                throw new NotFoundHttpException('页面不存在', 404);
            }
            $params['model'] = $model;
        }
        return parent::render($params, $view);
    }

    public function actions() {
        $cid = $this->getParam('cid', Post::CID_TECH);
        $actions = parent::actions();
        $actions['index'] = [
            'class' => 'app\actions\UserList',
            'title' => '探索未知',
            'where' => ['cid' => $cid, 'status' => Post::STATUS_YES],
            'modelClass' => Post::className()
        ];
        $actions['comment'] = [
            'class' => 'app\actions\PostCommentAction',
            'title' => '评论列表',
            'modelClass' => Comment::className(),
        ];
        $actions['like'] = [
            'class' => 'app\actions\LikeAction',
            'modelClass' => Post::className(),
            'own' => Like::OWN_POST
        ];
        return $actions;
    }

    public function actionDetail($id) {
        $model = Post::findOne($id);
        if (!$model) {
            return $this->redirect(['post/']);
        }

        $isLike = Like::getIsLike(Like::OWN_POST, $id, $this->getLikeId());

        $this->view->title = $model->title;
        return $this->render(compact('model', 'isLike'));
    }


}